"""
郑商所主力合约跳空高开的统计
先取主力合约的列表，然后取主力合约的数据，计算跳高跳低，再按主力时间去合并
"""
import pandas as pd
import rqdatac as rq
rq.init("13570866213", "39314656")
order_book_id = ["CF2001", "CF2005", "CF2009", "CF2101", "CF2105", "CY2001", "CY2005", "CY2009",
                 "CY2101", "CY2105", "FG2001", "FG2005", "FG2009", "FG2101", "FG2105", "MA2001",
                 "MA2005", "MA2009", "MA2101", "MA2105", "OI2001", "OI2005", "OI2009", "OI2101",
                 "OI2105", "RM2001", "RM2005", "RM2009", "RM2101", "RM2105", "SA2005", "SA2009",
                 "SA2101", "SA2105", "SR2001", "SR2005", "SR2009", "SR2101", "SR2105", "TA2001",
                 "TA2005", "TA2009", "TA2101", "TA2105", "ZC2001", "ZC2005", "ZC2009", "ZC2011",
                 "ZC2101", "ZC2105", "PF2105"]
symbol_dict = {}
for order_book_id in order_book_id:
    sec_id = order_book_id[:2]
    symbol_ids = symbol_dict.setdefault(sec_id, [])
    symbol_ids.append(order_book_id)
print(symbol_dict)

ins = pd.read_csv("E:\\MarketData\\Future\\all_future_instruments.csv", index_col="order_book_id", encoding="GBK")

result_list = []

for sec_id, contract_ids in symbol_dict.items():
    sec_df = None
    for contract_id in contract_ids:
        print(sec_id, contract_id)
        data = rq.get_price(contract_id, frequency="1m")
        data.reset_index(drop=False, inplace=True)
        data["real_date"] = data["datetime"].dt.strftime("%Y-%m-%d")
        data_group = data.groupby("real_date")
        data_open = data_group["open"].first()
        data_close = data_group["close"].last()
        contract_data = pd.DataFrame({"open":data_open, "close":data_close})
        contract_data["last_close"] = contract_data["close"].shift(1)
        contract_data["day_jump"] = contract_data["open"] - contract_data["last_close"]
        contract_data["symbol"] = sec_id
        contract_data["contract_id"] = contract_id
        if sec_df is None:
            sec_df = contract_data
        else:
            domain_start = ins.at[contract_id, "domain_start"]
            sec_df = sec_df.truncate(after=domain_start)
            contract_data = contract_data.truncate(before=domain_start)
            contract_data = contract_data.iloc[1:]
            sec_df = pd.concat([sec_df, contract_data])
    sec_df = sec_df.truncate(before="2020-01-01")
    result_list.append(sec_df)
all_result_df = pd.concat(result_list)
all_result_df.to_csv("D:\\daily work\\20210310 CZCE jump\\all_result.csv")


